<?php

namespace App\Jobs\Import;

use App\Models\Common\CatData\Video\Vcareacat;
use App\Models\Common\CatData\Video\Vccat;
use App\Models\Common\CatData\Video\Vccattag;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Common\Enumdata\Enumop\Video\Vlang;
use App\Models\Entity\Asset\Vlive\Vchan;
use App\Models\Entity\Asset\Vlive\Vcposter;
use App\Models\Entity\Asset\Vlive\Vcstream;
use App\Models\Entity\Asset\Vlive\Vepg;
use Carbon\Carbon;
use DB;
use Excel;
use FTP;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ImportVchanJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数
     *
     * @var int
     */
    public $tries = 3;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 3600;

    protected $path;
    protected $batchImportVchanHistory;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($path, $batchImportVchanHistory)
    {
        $this->path                    = $path;
        $this->batchImportVchanHistory = $batchImportVchanHistory;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $history = [];

        /**
         * 错误的行
         */
        // 编号
        $errorRow['no_empty']  = [];
        $errorRow['no_unique'] = [];
        // 服务商
        $errorRow['sp_empty'] = [];
        // 剧集名称
        $errorRow['name_empty'] = [];
        // 地区
        $errorRow['area_empty'] = [];
        // 分类
        $errorRow['ccat_empty'] = [];
        // 归类
        $errorRow['class_empty'] = [];
        // 语言/语种
        $errorRow['language_empty'] = [];
        // 开始时间
        $errorRow['start_at_empty'] = [];
        // 结束时间
        $errorRow['expiring_at_empty'] = [];
        // 时长
        $errorRow['duration_empty'] = [];
        // 简介
        $errorRow['short_desc_empty'] = [];
        // 直播源地址
        $errorRow['vcstream_empty'] = [];
        // 是否支持时迁
        $errorRow['timeshift_empty'] = [];
        // EPG地址
        $errorRow['vepg_path_empty']     = []; // excel EPG文件路径为空
        $errorRow['vepg_dir_not_exist']  = []; // ftp上视频目录不存在
        $errorRow['vepg_file_not_exist'] = []; // ftp上视频文件不存在
        // 海报
        $errorRow['vcposter_path_empty']     = []; // 海报路径为空
        $errorRow['vcposter_dir_not_exist']  = []; // ftp上海报目录不存在
        $errorRow['vcposter_file_not_exist'] = []; // ftp上海报文件不存在
        $errorRow['vcposter_file_tpl_error'] = []; // ftp上海报文件规格错误
        // 台标地址
        $errorRow['vlogo_path_empty']     = []; // excel EPG文件路径为空
        $errorRow['vlogo_dir_not_exist']  = []; // ftp上视频目录不存在
        $errorRow['vlogo_file_not_exist'] = []; // ftp上视频文件不存在

        // 总行数
        $rowsCount = 0;
        // 剧集成功的行数
        $successCount = 0;
        // 导入开始时间
        $starttime = microtime(true);
        // 开始使用内存
        $startMemory = memory_get_usage();
        // selectSheetsByIndex(0)->
        // 选中第一个Sheet, 这样第一行当做属性名
        Excel::load($this->path, function ($reader) use (&$errorRow, &$successCount, &$rowsCount, &$history) {
            // ftp连接, ftp文件目录【需要做成配置项】
            $basePath     = config('custom.base.ftp_vlive_director');
            $downloadPath = config('custom.base.download_path');
            $replaceDir   = config('custom.base.replace_dir');
            $ftp          = FTP::connection();

            // 1.方式1, 这种方法是从文件的第一行数据开始读，一直读取到最后。每行的数据在转化的数组里的下标都是按照先后顺序从零开始的。
            $reader = $reader->getSheet(0);
            //获取表中的数据
            $data = $reader->toArray();
            // 2.方式2, 这种方法从文件第二行开始读取
            // $data = $reader->get()->toArray();
            // $data = $reader->noHeading()->all()->toArray();// 获取到文件的表头信息
            // $data = $reader->ignoreEmpty()->all()->toArray();// 忽略空单元格
            // 获得所有数据
            // $data = $reader->all()->toArray();

            // 字段映射关系
            $fieldsMapping = [
                // 编号
                'no'          => 0,
                // 服务商
                'sp_id'       => 1,
                // 剧集名称
                'name'        => 2,
                // 产地/地区
                'areas'       => 3,
                // 分类
                'ccats'       => 4,
                // 归类
                'class'       => 5,
                // 语言
                'languages'   => 6,
                // 时长
                'duration'    => 7,
                // 源地址
                'vcstreams'   => 8,
                // 是否支持时移
                'timeshift'   => 9,
                // 台标地址
                'vlogo'       => 10,
                // 海报地址
                'vcposters'   => 11,
                // EPG地址
                'vepgs'       => 12,
                // 简介
                'short_desc'  => 13,
                // 详情
                'desc'        => 14,
                // 是否收费
                'charge_type' => 15,
                // 开始时间
                'start_at'    => 16,
                // 失效时间
                'expiring_at' => 17,
            ];

            // 总记录数
            $num = count($data);
            // 从哪行开始是数据
            $startRow = 1;
            // 总记录数
            $rowsCount = $num;
            // 第几行开始算【给用户提醒的行号】
            $rowNo = 1;
            // 批次自动生成
            $batch = date('YmdHis');

            for ($i = $startRow; $i < $num; $i++) {
                // 完成数+1
                // $this->batchImportVchanHistory->update([
                //     'done_count' => DB::raw("(`done_count`)"+ 1),
                // ]);

                // 完成数+1
                $this->batchImportVchanHistory->increment('done_count');
                // 每次插入开启事务
                DB::beginTransaction();
                try {

                    // 判断该条记录有没有问题
                    $flag = true;
                    // 编号
                    $no = '';
                    // 服务商
                    $sp_id = [];
                    // 直播媒资名称
                    $name = '';
                    // 产地/地区(直播媒资地区)
                    $areas = [];
                    // 分类
                    $ccats = [];
                    // 归类, 电影/电视剧
                    $class = '';
                    // 语言
                    $languages = [];
                    // 时长
                    $duration = '';
                    // 简介
                    $short_desc = '';
                    // 详情
                    $desc = '';
                    // 开始时间
                    $start_at = '';
                    // 结束时间
                    $expiring_at = '';
                    // 台标地址
                    $vlogo_path = '';
                    // 海报文件目录
                    $vcposter_path = '';
                    $vcposters     = [];
                    // epg地址
                    $vepg_path = '';
                    $vepgs     = [];
                    // 直播源地址
                    $vcstream_path = '';
                    $vcstreams     = [];
                    // 台标地址
                    $vlogo = '';
                    // 收费类型
                    $charge_type = '';

                    // 编号不能为空
                    if (isset($data[$i][$fieldsMapping['no']])) {
                        $no = trim($data[$i][$fieldsMapping['no']]);
                    }
                    if (empty($no)) {
                        $flag                   = false;
                        $errorRow['no_empty'][] = ($i + $rowNo);
                    }

                    // 编号唯一【排除它是分集】
                    if (Vchan::where('vchan_no', $no)->first()) {
                        $flag                    = false;
                        $errorRow['no_unique'][] = ($i + $rowNo);
                    }

                    // 服务商
                    if (isset($data[$i][$fieldsMapping['sp_id']])) {
                        $sp_id = trim($data[$i][$fieldsMapping['sp_id']]);
                    }
                    if (empty($sp_id)) {
                        $flag                   = false;
                        $errorRow['sp_empty'][] = ($i + $rowNo);
                    } else {
                        // 需要将服务商转成id
                        if ($sp1 = Sp::where('name', $sp_id)->first()) {
                            $sp_id = $sp1->id;
                        } else {
                            $sp             = new Sp;
                            $sp->name       = $sp_id;
                            $sp->short_desc = $sp_id;
                            $sp->save();
                            $sp_id = $sp->id;
                        }
                    }

                    // 简介
                    $short_desc = '';
                    if (isset($data[$i][$fieldsMapping['short_desc']])) {
                        $short_desc = trim($data[$i][$fieldsMapping['short_desc']]);
                    }
                    if (empty($short_desc)) {
                        $flag                           = false;
                        $errorRow['short_desc_empty'][] = ($i + $rowNo);
                    }

                    // 详情
                    $desc = '';
                    if (isset($data[$i][$fieldsMapping['desc']])) {
                        $desc = trim($data[$i][$fieldsMapping['desc']]);
                    }
                    // 开始时间
                    $start_at = '';
                    if (isset($data[$i][$fieldsMapping['start_at']])) {
                        $start_at = trim($data[$i][$fieldsMapping['start_at']]);
                        $start_at = Carbon::parse($start_at)->timestamp;
                        $start_at = date('Y-m-d H:i:s', $start_at);
                    }
                    if (empty($start_at)) {
                        $flag                         = false;
                        $errorRow['start_at_empty'][] = ($i + $rowNo);
                    }
                    // 结束时间
                    if (isset($data[$i][$fieldsMapping['expiring_at']])) {
                        $expiring_at = trim($data[$i][$fieldsMapping['expiring_at']]);
                        $expiring_at = Carbon::parse($expiring_at)->timestamp;
                        $expiring_at = date('Y-m-d H:i:s', $expiring_at);
                    }
                    if (empty($expiring_at)) {
                        $flag                            = false;
                        $errorRow['expiring_at_empty'][] = ($i + $rowNo);
                    }
                    // 时长, 默认给60, 时长是给文件的
                    $duration = 0;
                    if (isset($data[$i][$fieldsMapping['duration']])) {
                        $duration = trim($data[$i][$fieldsMapping['duration']]);
                    }
                    // if (empty($duration)) {
                    //     $flag                         = false;
                    //     $errorRow['duration_empty'][] = ($i + $rowNo);
                    // }

                    // 台标地址
                    if (isset($data[$i][$fieldsMapping['vlogo']])) {
                        $vlogo_path = trim($data[$i][$fieldsMapping['vlogo']]);
                        $vlogo_path = iconv('utf-8', 'gbk', $vlogo_path);
                    }
                    if (empty($vlogo_path)) {

                    } else {
                        $files = $ftp->getDirListing($basePath . '/' . $vlogo_path);
                        var_dump($files);
                        if ($files && $flag) {
                            foreach ($files as $key => $fileValue) {
                                $fileValue = iconv('gbk', 'utf-8', $fileValue);
                                $fileValue = str_replace($replaceDir, "", $fileValue);
                                $vlogo     = $fileValue;
                                break;
                            }
                        } else {
                            // 台标文件目录不存在
                            $flag                               = false;
                            $errorRow['vlogo_file_not_exist'][] = ($i + $rowNo);
                        }
                        if (empty($files)) {
                            // 台标文件不存在
                            $flag                              = false;
                            $errorRow['vlogo_dir_not_exist'][] = ($i + $rowNo);
                        }
                    }
                    // 海报地址
                    if (isset($data[$i][$fieldsMapping['vcposters']])) {
                        $vcposter_path = trim($data[$i][$fieldsMapping['vcposters']]);
                        $vcposter_path = iconv('utf-8', 'gbk', $vcposter_path);
                    }
                    if (empty($vcposter_path)) {
                        // $flag                           = false;
                        // $errorRow['photo_path_empty'][] = ($i + $rowNo);
                    } else {
                        $files = $ftp->getDirListing($basePath . '/' . $vcposter_path);
                        if ($files && $flag) {
                            $separator = '/';
                            $vcposters = [];
                            foreach ($files as $fileValue) {
                                $file = iconv('gbk', 'utf-8', $fileValue);
                                // 判断是否为图片
                                if (preg_match('/.*?\.(jpg|jpeg|png|gif)$/', $file)) {
                                    $imgFileInfo = [];
                                    // 文件名
                                    $name = '';
                                    // 图片类型, 1 => 海报, 2 => 剧照
                                    // $imgtag = '';
                                    // 图片规格, 1 => BIMG, 2 => MIMG, 3 => SIMG, 4 => TB
                                    $imgtpl = '';
                                    // 图片路径
                                    $filePath     = $file;
                                    $fullFileName = substr(strrchr($file, "/"), 1);
                                    $aFileNames   = explode('@', $fullFileName);
                                    $name         = substr($fullFileName, 0, strrpos($name, "@"));
                                    // 排序字段
                                    $listorder = 0;
                                    // 文件名称
                                    $name = $fullFileName;
                                    if (strpos($name, ".") !== false) {
                                        $name = substr($name, 0, strrpos($name, "."));
                                    }
                                    if (strpos($name, "@") !== false) {
                                        $name = substr($name, 0, strpos($name, "@"));
                                    }
                                    // 正则区分是海报/剧照 和 图片规格
                                    if (preg_match('/.*?@(TB|tb)(\\d*)\.(jpg|jpeg|png|gif)$/', $fullFileName)) {
                                        $imgtpl = 4;
                                        // /php/i, 使用了i 修正符, 不区分大小写去文本中匹配
                                        // preg_match() 第一次匹配成功后就会停止匹配，如果要实现全部结果的匹配preg_match_all()
                                        // .是任意字符
                                        // .?的意思是尽可能少的匹配
                                        // .*具有贪婪的性质，首先匹配到不能匹配为止，根据后面的正则表达式，会进行回溯。
                                        // .*?则相反，一个匹配以后，就往下进行，所以不会进行回溯，具有最小匹配的性质。

                                        // tian modify 2017/08/22
                                        if (preg_match('/.*?@(TB|tb)(\\d+)\.(jpg|jpeg|png|gif)$/', $fullFileName)) {
                                            $listorder = substr($fullFileName, strrpos($fullFileName, "@") + 1);
                                            $listorder = substr($listorder, 0, strrpos($listorder, "."));
                                            $listorder = substr($listorder, 2);
                                        }
                                    } else if (preg_match('/.*?@(BIMG|bimg)\.(jpg|jpeg|png|gif)$/', $fullFileName)) {
                                        $imgtag = 1;
                                        $imgtpl = 1;
                                    } else if (preg_match('/.*?@(MIMG|mimg)\.(jpg|jpeg|png|gif)$/', $fullFileName)) {
                                        $imgtpl = 2;
                                    } else if (preg_match('/.*?@(SIMG|simg)\.(jpg|jpeg|png|gif)$/', $fullFileName)) {
                                        $imgtpl = 3;
                                    }

                                    if (empty($imgtpl)) {
                                        $errorRow['vcposter_file_tpl_error'][] = ($i + $rowNo);
                                        // dd("图片规格不存在");
                                    }
                                    if (!empty($imgtpl)) {
                                        // 新建图片
                                        $vcposter                = new Vcposter;
                                        $vcposter->vcposter_no   = 1;
                                        $vcposter->name          = $name;
                                        $vcposter->title         = $name;
                                        $vcposter->subtitle      = $name;
                                        $filePath                = str_replace($replaceDir, "", $filePath);
                                        $vcposter->cposter_url   = $filePath;
                                        $vcposter->specification = $imgtpl;
                                        $vcposter->listorder     = $listorder;
                                        if ($vcposter->save()) {
                                            $vcposters[] = $vcposter->id;
                                        }
                                    }

                                }
                            }
                            if (empty($vcposters)) {
                                // 没有图片文件
                                $flag                                  = false;
                                $errorRow['vcposter_file_not_exist'][] = ($i + $rowNo);
                            }
                        } else {
                            // 图片文件目录不存在
                            $flag                                 = false;
                            $errorRow['vcposter_dir_not_exist'][] = ($i + $rowNo);
                        }
                    }

                    // 直播媒资名称
                    if (isset($data[$i][$fieldsMapping['name']])) {
                        $name = trim($data[$i][$fieldsMapping['name']]);
                    }
                    if (empty($name)) {
                        $flag                     = false;
                        $errorRow['name_empty'][] = ($i + $rowNo);
                    }

                    // 产地/地区(直播媒资地区)
                    if (isset($data[$i][$fieldsMapping['areas']])) {
                        $areas = trim($data[$i][$fieldsMapping['areas']]);
                    }
                    if (empty($areas)) {
                        $flag                     = false;
                        $errorRow['area_empty'][] = ($i + $rowNo);
                    } else {
                        // 对产地进行处理, 按照 `&` 裁剪
                        $aAreas = explode('&', $areas);
                        $areas  = [];
                        foreach ($aAreas as $key => $value) {
                            if ($varea1 = Vcareacat::where('name', $value)->first()) {
                                $areas[] = $varea1->id;
                            } else {
                                $varea               = new Vcareacat;
                                $varea->vcareacat_no = 1;
                                $varea->name         = $value;
                                $varea->title        = $value;
                                $varea->short_desc   = $value;
                                $varea->save();
                                $areas[] = $varea->id;
                            }
                        }
                    }

                    // 归类, 电影/电视剧
                    $class = '';
                    if (isset($data[$i][$fieldsMapping['class']])) {
                        $class = trim($data[$i][$fieldsMapping['class']]);
                    }
                    if (empty($class)) {
                        $flag                      = false;
                        $errorRow['class_empty'][] = ($i + $rowNo);
                    } else {
                        // 需要将归类转成id
                        if ($vccat1 = Vccat::where('name', $class)->first()) {
                            $class = $vccat1->id;
                        } else {
                            $vccat             = new Vccat;
                            $vccat->name       = $class;
                            $vccat->short_desc = $class;
                            $vccat->save();
                            $class = $vccat->id;
                        }
                    }

                    // 分类
                    if (isset($data[$i][$fieldsMapping['ccats']])) {
                        $ccats = trim($data[$i][$fieldsMapping['ccats']]);
                    }
                    if (empty($ccats)) {
                        $flag                     = false;
                        $errorRow['ccat_empty'][] = ($i + $rowNo);
                    } else {
                        // 对分类进行处理, 按照 `&` 裁剪
                        $aCcats = explode('&', $ccats);
                        $ccats  = [];
                        foreach ($aCcats as $key => $value) {
                            if ($ccat1 = Vccattag::where(['name' => $value, 'vccat_id' => $class])->first()) {
                                $ccats[] = $ccat1->id;
                            } else {
                                $ccat           = new Vccattag;
                                $ccat->name     = $value;
                                $ccat->vccat_id = $class;
                                $ccat->save();
                                $ccats[] = $ccat->id;
                            }
                        }
                    }
                    // 语言/语种
                    $languages = [];
                    if (isset($data[$i][$fieldsMapping['languages']])) {
                        $languages = trim($data[$i][$fieldsMapping['languages']]);
                    }
                    if (empty($languages)) {
                        $flag                         = false;
                        $errorRow['language_empty'][] = ($i + $rowNo);
                    } else {
                        // 对语种进行处理, 按照 `&` 裁剪
                        $aLanguages = explode('&', $languages);
                        $languages  = [];
                        foreach ($aLanguages as $key => $value) {
                            if ($language1 = Vlang::where('name', $value)->first()) {
                                $languages[] = $language1->id;
                            } else {
                                $language             = new Vlang;
                                $language->name       = $value;
                                $language->short_desc = $value;
                                $language->save();
                                $languages[] = $language->id;
                            }
                        }
                    }

                    // epg地址
                    if (isset($data[$i][$fieldsMapping['vepgs']])) {
                        $vepg_path = trim($data[$i][$fieldsMapping['vepgs']]);
                        $vepg_path = iconv('utf-8', 'gbk', $vepg_path);
                    }
                    if (empty($vepg_path)) {
                        // $flag                           = false;
                        // $errorRow['video_path_empty'][] = ($i + $rowNo);
                    } else {
                        $files = $ftp->getDirListing($basePath . '/' . $vepg_path);
                        if ($files && $flag) {
                            $separator = '/';
                            $vepgs     = [];
                            foreach ($files as $key => $file) {
                                $file                = iconv('gbk', 'utf-8', $fileValue);
                                $vepg                = new Vepg;
                                $vepg->vepg_no       = 1;
                                $vepg->name          = $name;
                                $vepg->title         = $name;
                                $vepg->subtitle      = $name;
                                $vepg->epg_url       = $vepg_path;
                                $vepg->epg_format_id = 1;
                                $vepg->start_time    = $start_at;
                                $vepg->end_time      = $expiring_at;
                                $vepg->save();
                                $vepgs[] = $vepg->id;
                            }
                        } else {
                            $flag                             = false;
                            $errorRow['vepg_dir_not_exist'][] = ($i + $rowNo);
                        }
                    }

                    // 收费类型
                    if (isset($data[$i][$fieldsMapping['charge_type']])) {
                        $charge_type = $data[$i][$fieldsMapping['charge_type']];
                        if ($charge_type == '否') {
                            $charge_type = 0;
                        } else {
                            $charge_type = 1;
                        }
                    }

                    // 保存直播媒资信息
                    if ($flag) {
                        $vchan = new Vchan;
                        // 编号
                        $vchan->vchan_no = $no;
                        // 剧集名称
                        $vchan->name = $name;
                        // 简介
                        $vchan->short_desc = $short_desc;
                        // 详情
                        $vchan->long_desc = $desc;
                        // 归类
                        $vchan->vccat_id = $class;
                        // 台标地址
                        $vchan->vlogo = $vlogo;
                        // 标题和副标题都当处理
                        $vchan->title    = $name;
                        $vchan->subtitle = $name;
                        // 收费类型
                        $vchan->charge_type = $charge_type;
                        // 开始时间
                        $vchan->start_at = $start_at;
                        // 结束时间
                        $vchan->expiring_at = $expiring_at;
                        $flag               = $vchan->save();
                        // 直播源地址
                        if (isset($data[$i][$fieldsMapping['vcstreams']])) {
                            $vcstream_path = trim($data[$i][$fieldsMapping['vcstreams']]);
                        }
                        if (empty($vcstream_path)) {
                            $flag                         = false;
                            $errorRow['vcstream_empty'][] = ($i + $rowNo);
                        } else {
                            // 清晰度, 默认给6
                            $resolution     = 6;
                            $resolutionName = substr($vcstream_path, strrpos($vcstream_path, ":") + 1);
                            $name           = trim($data[$i][$fieldsMapping['name']]);
                            if (isset($data[$i][$fieldsMapping['vcstreams']])) {
                                $timeshift = trim($data[$i][$fieldsMapping['timeshift']]);
                            }
                            if (empty($timeshift)) {
                                $flag                          = false;
                                $errorRow['timeshift_empty'][] = ($i + $rowNo);
                            } else if ($timeshift == '是') {
                                $timeshift = 1;
                            } else {
                                $timeshift = 0;
                            }
                            // 时长,默认给60
                            $duration = 60;
                            if ($resolutionName == 'sd') {
                                $vcstream                = new Vcstream;
                                $vcstream->cstream_no    = 1;
                                $vcstream->name          = $name;
                                $vcstream->title         = $name;
                                $vcstream->subtitle      = $name;
                                $vcstream->timeshift     = $timeshift;
                                $vcstream->type          = 1;
                                $vcstream->url           = $vcstream_path;
                                $vcstream->duration      = $duration;
                                $vcstream->resolution_id = 6;
                                $vcstream->listorder     = 0;
                                $vcstream->vchan_id      = $vchan->id;
                                $vcstream->save();
                                $vcstreams[] = $vcstream->id;
                            }
                        }
                        // 还要判断是分集还是总集
                        if ($flag) {
                            // 服务商
                            if (!empty($sp_id)) {
                                $vchan->sps()->sync([$sp_id]);
                            }
                            // 海报
                            if (!empty($vcposters)) {
                                $vchan->vcposters()->sync($vcposters);
                            }
                            // 直播源
                            if (!empty($vcstreams)) {
                                $vchan->vcstreams()->sync($vcstreams);
                            }
                            // 地区
                            if (!empty($areas)) {
                                $vchan->vcareacats()->sync($areas);
                            }
                            // EPG
                            if (!empty($vepgs)) {
                                $vchan->vepgs()->sync($vepgs);
                            }
                            // 语种
                            if (!empty($languages)) {
                                $vchan->vlangs()->sync($languages);
                            }
                            // 分类
                            if (!empty($ccats)) {
                                $vchan->vccattags()->sync($ccats);
                            }
                        }
                        // 成功的行数
                        $successCount++;
                    }

                    if ($flag) {
                        DB::commit();
                    } else {
                        DB::rollback();
                    }
                    // DB::commit();
                } catch (\Exception $e) {
                    DB::rollback(); // 事务回滚
                    echo $e->getMessage();
                    dd($e->getCode());
                }
            }
            //组合记录导入日志数据
            $history['batch'] = $batch;
            $history['count'] = $num - 1;

        });
        // 错误数据的行号
        $allErrorRows = [];
        $allErrorRows = array_unique(array_merge(
            // 编号
            $errorRow['no_empty'],
            $errorRow['no_unique'],
            // 服务商
            $errorRow['sp_empty'],
            // 剧集名称
            $errorRow['name_empty'],
            // 地区
            $errorRow['area_empty'],
            // 分类
            $errorRow['ccat_empty'],
            // 归类
            $errorRow['class_empty'],
            // 语言/语种
            $errorRow['language_empty'],
            // 时长
            $errorRow['duration_empty'],
            // 简介
            $errorRow['short_desc_empty'],
            // 开始时间
            $errorRow['start_at_empty'],
            // 结束时间
            $errorRow['expiring_at_empty'],
            // 直播源地址
            $errorRow['vcstream_empty'],
            // EPG地址
            $errorRow['vepg_path_empty'], // excel EPG文件路径为空
            $errorRow['vepg_dir_not_exist'], // ftp上视频目录不存在
            $errorRow['vepg_file_not_exist'], // ftp上视频文件不存在
            // 海报
            $errorRow['vcposter_path_empty'], // 海报路径为空
            $errorRow['vcposter_dir_not_exist'], // ftp上海报目录不存在
            $errorRow['vcposter_file_not_exist'], // ftp上海报文件不存在
            $errorRow['vcposter_file_tpl_error'], // ftp上海报文件规格错误
            // 台标地址
            $errorRow['vlogo_path_empty'], // excel EPG文件路径为空
            $errorRow['vlogo_dir_not_exist'], // ftp上视频目录不存在
            $errorRow['vlogo_file_not_exist']// ftp上视频文件不存在
        ));

        $errorCount = count($allErrorRows);
        // 导入结束时间
        $endtime        = microtime(true);
        $consuming_time = round($endtime - $starttime, 4);
        $endMemory      = memory_get_usage();
        $usedMemory     = ($endMemory - $startMemory) / 1024;

        // $history['consuming_time'] = $consuming_time;
        // 写批量导入媒资的日志表
        // BatchImportUserHistory::create($history);

        $flag    = true;
        $message = '<div style="word-wrap: break-word;">';
        $message .= '耗时:';
        $message .= $consuming_time . '秒<br />';
        $message .= '耗费内存:';
        $message .= "{$usedMemory} K<br />";

        $message .= '数据总数:';
        $message .= $history['count'] . '行<br />';
        $message .= '直播媒资成功的行数:';
        $message .= $successCount . '行<br />';
        $message .= '错误的总行数:';
        $message .= $errorCount . '行<br />';

        // 编号
        if (count($errorRow['no_empty']) > 0) {
            $flag = false;
            $message .= '编号为空[no_empty]的行号:' . implode(',', $errorRow['no_empty']) . '<br />';
        }
        // 编号不唯一
        if (count($errorRow['no_unique']) > 0) {
            $flag = false;
            $message .= '编号不唯一[no_unique]的行号:' . implode(',', $errorRow['no_unique']) . '<br />';
        }
        // 服务商
        if (count($errorRow['sp_empty']) > 0) {
            $flag = false;
            $message .= '服务商为空[sp_empty]的行号:' . implode(',', $errorRow['sp_empty']) . '<br />';
        }
        // 直播媒资名称
        if (count($errorRow['name_empty']) > 0) {
            $flag = false;
            $message .= '剧集名称为[name_empty]空的行号:' . implode(',', $errorRow['name_empty']) . '<br />';
        }
        // 地区
        if (count($errorRow['area_empty']) > 0) {
            $flag = false;
            $message .= '产地为空[area_empty]的行号:' . implode(',', $errorRow['area_empty']) . '<br />';
        }
        // // 分类
        // if (count($errorRow['cat_empty']) > 0) {
        //     $flag = false;
        //     $message .= '分类为空[cat_empty]的行号:' . implode(',', $errorRow['cat_empty']) . '<br />';
        // }
        // 归类
        if (count($errorRow['class_empty']) > 0) {
            $flag = false;
            $message .= '归类为空[class_empty]的行号:' . implode(',', $errorRow['class_empty']) . '<br />';
        }
        // // 语言/语种
        // if (count($errorRow['language_empty']) > 0) {
        //     $flag = false;
        //     $message .= '语言为空[language_empty]的行号:' . implode(',', $errorRow['language_empty']) . '<br />';
        // }
        // 时长
        if (count($errorRow['duration_empty']) > 0) {
            $flag = false;
            $message .= '时长为空[duration_empty]的行号:' . implode(',', $errorRow['duration_empty']) . '<br />';
        }
        // 简介
        if (count($errorRow['short_desc_empty']) > 0) {
            $flag = false;
            $message .= '简介为空[short_desc_empty]的行号:' . implode(',', $errorRow['short_desc_empty']) . '<br />';
        }
        // 直播源地址
        if (count($errorRow['vcstream_empty']) > 0) {
            $flag = false;
            $message .= '直播源地址为空[vcstream_empty]的行号:' . implode(',', $errorRow['vcstream_empty']) . '<br />';
        }
        // 是否支持时迁
        if (count($errorRow['timeshift_empty']) > 0) {
            $flag = false;
            $message .= '是否支持时迁为空[timeshift_empty]的行号:' . implode(',', $errorRow['timeshift_empty']) . '<br />';
        }
        // EPG文件
        if (count($errorRow['vepg_path_empty']) > 0) {
            $flag = false;
            $message .= 'excel(EPG地址)为空[vepg_path_empty]的行号:' . implode(',', $errorRow['vepg_path_empty']) . '<br />';
        }
        if (count($errorRow['vepg_dir_not_exist']) > 0) {
            $flag = false;
            $message .= 'ftp上(EPG文件目录)不存在[vepg_dir_not_exist]的行号:' . implode(',', $errorRow['vepg_dir_not_exist']) . '<br />';
        }
        if (count($errorRow['vepg_file_not_exist']) > 0) {
            $flag = false;
            $message .= 'ftp上(EPG文件)不存在[vepg_file_not_exist]的行号:' . implode(',', $errorRow['vepg_file_not_exist']) . '<br />';
        }
        // 海报
        if (count($errorRow['vcposter_path_empty']) > 0) {
            $flag = false;
            $message .= 'excel(海报文件目录)为空[vcposter_path_empty]的行号:' . implode(',', $errorRow['vcposter_path_empty']) . '<br />';
        }
        if (count($errorRow['vcposter_dir_not_exist']) > 0) {
            $flag = false;
            $message .= 'ftp上(海报目录)不存在[vcposter_dir_not_exist]的行号:' . implode(',', $errorRow['vcposter_dir_not_exist']) . '<br />';
        }
        if (count($errorRow['vcposter_file_not_exist']) > 0) {
            $flag = false;
            $message .= 'ftp上(海报文件)不存在[vcposter_file_not_exist]的行号:' . implode(',', $errorRow['vcposter_file_not_exist']) . '<br />';
        }
        if (count($errorRow['vcposter_file_tpl_error']) > 0) {
            $flag = false;
            $message .= 'ftp上(海报文件)规格错误[vcposter_file_tpl_error]的行号:' . implode(',', $errorRow['vcposter_file_tpl_error']) . '<br />';
        }
        if (count($errorRow['vlogo_dir_not_exist']) > 0) {
            $flag = false;
            $message .= 'ftp上(台标目录)不存在[vlogo_dir_not_exist]的行号:' . implode(',', $errorRow['vlogo_dir_not_exist']) . '<br />';
        }
        if (count($errorRow['vlogo_file_not_exist']) > 0) {
            $flag = false;
            $message .= 'ftp上(台标文件)不存在[vlogo_file_not_exist]的行号:' . implode(',', $errorRow['vlogo_file_not_exist']) . '<br />';
        }
        if (count($errorRow['start_at_empty']) > 0) {
            $flag = false;
            $message .= '开始时间为空[start_at_empty]的行号:' . implode(',', $errorRow['start_at_empty']) . '<br />';
        }
        if (count($errorRow['expiring_at_empty']) > 0) {
            $flag = false;
            $message .= '结束时间为空[expiring_at_empty]的行号:' . implode(',', $errorRow['expiring_at_empty']) . '<br />';
        }
        $message .= '</div>';
        //通过标志位判断前端返回时成功还是失败
        if ($flag) {
            $message = '<div class="alert alert-success">' . $message . '</div>';
        } else {
            $message = '<div class="alert alert-error">' . $message . '</div>';
        }
        $this->batchImportVchanHistory->success_count  = $successCount;
        $this->batchImportVchanHistory->error_count    = $errorCount;
        $this->batchImportVchanHistory->consuming_time = $consuming_time;
        $this->batchImportVchanHistory->used_memory    = $usedMemory;
        $this->batchImportVchanHistory->content        = $message;
        $this->batchImportVchanHistory->save();
    }
}
